<?php

namespace App\Console\Commands;

use App\models\AdminModule;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class AdminCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qx-admin';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化系统后台权限数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
       $modules = glob('app/Http/Controllers/*');
       foreach ($modules as $module)
       {
           if ($this->isModule($module))
           {
//               创建模块表
               $this->createModule($module);
//                创建权限表
               $this->createPermission($module);
               //               给站长添加所有权限
               $this->assignPermission($module);
           }
       }
//       手动清除缓存
        app()['cache']->forget('spatie.permission.cache');
       $this->info('命令执行成功');
    }

//    检查模块是否合法，是否有config目录下的app.php文件
     public function isModule(string $module):bool
     {
         return is_file($module.'/config/app.php');
     }

//     创建模块方法
      public function createModule(string $name)
      {
          $config = include $name . '/config/app.php';
          $config['config'] = $config;
          $config['module'] = basename($name);
          $config['permission'] = $this->getModulePermission($name);
          AdminModule::firstOrNew(['module'=>$config['module']])->fill($config)->save();
          return true;
      }
//      获取模块权限
      public function getModulePermission(string $name)
      {
         $file = $name . '/config/permission.php';
//         先判断这个文件在模块中是否存在
          if (is_file($file))
          {
              $permissions = include $file;
              foreach ($permissions as $key=>$permission)
              {
                  $permissions[$key]['name'] = basename($name).'-'.$permission['name'];
              }
              return $permissions;
          }
          return [];
      }
//      创建模块权限数据
    public function createPermission(string $name){
        foreach ($this->getModulePermission($name) as $permission){
            $permission['guard_name'] = 'admin';
            Permission::firstOrNew(['name'=>$permission['name']])->fill($permission)->save();
        }
    }
//    给站长分配所有权限
    public function assignPermission(string $name){
        foreach($this->getModulePermission($name) as $permission){
            (Role::first())->givePermissionTo($permission['name']);
        }
    }
}
